package com.itheima;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.Arrays;

public class IOStreamTest {
    @Test
    public void testInputStream() throws IOException {
        InputStream is = new FileInputStream("src\\main\\java\\com\\itheima\\fileTest.txt");
        int b1 = is.read();
        System.out.println(b1);
        int b;
        while ((b = is.read()) != -1) {
            System.out.print((char) b);
        }
        is.close();
    }

    @Test
    public void testOutputStream() throws IOException {
        InputStream is = new FileInputStream("src\\main\\java\\com\\itheima\\fileTest.txt");
        byte[] buffer  = new byte[5];
//        System.out.println(Arrays.toString(buffer));
//        int len = is.read(buffer);
//        System.out.println(new String(buffer));
        int len;
        while((len = is.read(buffer)) != -1) {
            System.out.println(new String(buffer, 0, len));
        }
        is.close();
    }

    @Test
    public void testStream() throws Exception {
        InputStream is = new FileInputStream("src/main/java/com/itheima/fileTest.txt"); // 基础流
        InputStream bis = new BufferedInputStream(is); // 缓冲流 默认8kb
        byte[] buffer = bis.readAllBytes();
        System.out.println(new String(buffer));
    }

    @Test
    public void testOutput() throws Exception {
        // 写入字符
        // 第二个参数表示是否覆盖
//        OutputStream os = new FileOutputStream("src/main/java/com/itheima/fileTest.txt", true);
//        os.write(97);
//        os.write('b');
//        os.write("\r\n".getBytes());
//        byte[] bytes = "飒飒".getBytes();
//        os.write(bytes);
//        os.close();

        try (
                OutputStream os = new FileOutputStream("src/main/java/com/itheima/fileTest.txt");
                OutputStream bos = new BufferedOutputStream(os);
        ) {
            bos.write(97);
            bos.write('b');
            bos.write("\r\n".getBytes());
            byte[] bytes = "飒飒".getBytes();
            bos.write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
